import axios from "axios";
import React, { Fragment } from "react";
// import Footer from "./common/Footer";
// import Main from "./common/Main";
// import Header from "./common/Header";

// const TodoList = () => {
//   return (
//     <Fragment>
      
//     </Fragment>
//   );
// };


class MyInput extends React.Component {

  render () {
    return (
      <div>
        <form>
          <label htmlFor="input">请输入：</label>
          <input 
            id="input" 
            value={this.props.value}
            onDragEnterCapture={this.props.addItem}
            onChange={this.props.change}/>
          <button onClick={this.props.addItem}>提交</button>
        </form>
      </div>
    )
  }
  
}

class TodoItem extends React.Component {
  
  render () {
    return (
      <div onClick={this.props.removeItem}>{this.props.content}</div>
    )
  }

}


export default class TodoList extends React.Component {

  constructor (props) {
    super(props)
    const list = JSON.parse(localStorage.getItem('tadolist')) || []
    this.state = {
      list,
      value: ''
    }
    this.changeInput = this.changeInput.bind(this)
    this.addItem = this.addItem.bind(this)  
    // this.removeItem = this.removeItem.bind(this)
  }

  changeInput (e) {
    const value = e.target.value
    this.setState(() => ({
      value: value
    }))
  }

  addItem (e) {
    e.preventDefault()
    const { value, list } = this.state
    if (!value) return
    list.unshift(value)
    this.setTodo(list)
    this.setState({
      list,
      value: ''
    })
  }

  removeItem (index) {
    const { list } = this.state
    list.splice(index, 1)
    this.setTodo(list)
    this.setState({
      list
    })
  }

  setTodo (todo) {
    const NAME = 'tadolist'
    const list = JSON.stringify(todo || null)
    localStorage.setItem(NAME, list)
  }

  render () {
    return (
      <Fragment>
        <MyInput
          value={this.state.value}
          change={this.changeInput}
          addItem={this.addItem}
          />
        {this.renderItem()}
      </Fragment>
    )
  }

  renderItem () {
    const { list } = this.state
    return list.map((item, index) => (
      <TodoItem 
        key={index} 
        id={index} 
        content={item} 
        removeItem={this.removeItem.bind(this, index)}
      />
    ))
  }

  async componentDidMount () {
    const data = await axios.get('/api/todolist')
    console.log(data)
  }

}
